package cn.slahser.server;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;

import cn.slahser.tools.ServerConfig;

/***
 * 本服务器不做长时间连接
 * 
 * @author Slahser
 * 
 */
public class FileServer extends Thread {
	private Socket socket = null;
	static ServerSocket server = null;
	static boolean b = true;

	public void run() {
		try {
			InputStream in = socket.getInputStream();
			OutputStream out = socket.getOutputStream();
			File outputFile = null;
			// 缓冲
			byte[] b = new byte[1000];
			in.read(b);
			// download,[image,amr],xixihaha.jpg
			// upload,[image,amr],50
			String cmd = new String(b).trim();

			/***
			 * 下载相关
			 */
			if (cmd.startsWith("download")) {
				String[] ss = cmd.split(",");
				// 第二块是文件名
				String filename = ss[2];
				if (ss[1].equalsIgnoreCase("image")) {
					// 组合出一个路径
					outputFile = new File(
							ServerConfig.getValue("output_image_path"),
							filename);
				} else if (ss[1].equalsIgnoreCase("amr")) {
					outputFile = new File(
							ServerConfig.getValue("output_amr_path"), filename);
				}
				out.write((outputFile.length() + "").getBytes());
				// 清空缓冲
				out.flush();

				// 读取缓冲，再写出去给客户端
				FileInputStream fin = new FileInputStream(outputFile);
				in.read(b);
				int len = 0;
				// 清空缓冲
				byte[] b2 = new byte[1024];
				while ((len = fin.read(b2)) != -1) {
					out.write(b2, 0, len);
					out.flush();
				}
				fin.close();
				/***
				 * 上传相关
				 */
			} else if (cmd.startsWith("upload")) {
				// upload,[image,amr],50
				String[] ss = cmd.split(",");
				// 第二块这次是long
				long length = Long.parseLong(ss[2]);
				String filename = "";
				// 上传图片
				if (ss[1].equalsIgnoreCase("image")) {
					// 服务器随机抽取名称
					filename = new Date().getTime() + "R"
							+ (int) (Math.random() * 1000) + "R"
							+ (int) (Math.random() * 1000) + ".jpg";
					// 输出文件
					outputFile = new File(
							ServerConfig.getValue("output_image_path"),
							filename);
					// 上传音频
				} else if (ss[1].equalsIgnoreCase("amr")) {
					filename = new Date().getTime() + "R"
							+ (int) (Math.random() * 1000) + "R"
							+ (int) (Math.random() * 1000) + ".amr";
					outputFile = new File(
							ServerConfig.getValue("output_amr_path"), filename);
				}
				// 写出回应ok+文件名
				out.write(("ok," + filename).getBytes());
				// 清空缓存
				out.flush();
				// 开始传递出去，向磁盘输出
				FileOutputStream outs = new FileOutputStream(outputFile);
				int len = 0;
				long size = 0;
				byte[] b2 = new byte[1024];
				while ((len = in.read(b2)) != -1) {
					// 写出去写到大小超过文件大小，则break；
					if (size >= length) {
						break;
					}
					outs.write(b2, 0, len);
					size += len;
				}
				outs.flush();
				outs.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				socket.close();
			} catch (IOException e) {
			}
		}
	}

	public static void openServer() throws Exception {
		try {
			server = new ServerSocket(Integer.parseInt(ServerConfig
					.getValue("file_server_port")));
			while (b) {
				new FileServer(server.accept()).start();
			}
		} catch (Exception ex) {
			ex.printStackTrace();
			try {
				server.close();
			} catch (Exception e) {
			}
			throw ex;
		}
	}

	public static void closeServer() throws Exception {
		try {
			b = false;
			server.close();
		} catch (Exception ex) {
			throw ex;
		}
	}

	public FileServer(Socket socket) {
		this.socket = socket;
	}

}
